package com.hzlh.core.interceptor;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.hzlh.core.utils.StringPrintWriter;
  
public class ExceptionHandler implements HandlerExceptionResolver {

	private static final Logger logger = Logger.getLogger(ExceptionHandler.class);
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		if(ex != null){
			String url = request.getRequestURI();
			String method = request. getMethod();
			Map<String, String[]> params = request.getParameterMap();  
			String param = "";
			StringBuffer str = new StringBuffer("");  
			for (String key : params.keySet()) {
				String[] values = params.get(key);
			    for (int i = 0; i < values.length; i++) {
			    	String value = values[i];  
			    	str.append(key +"="+ value +",");
			    }  
			}
			if(str.length() > 0){
				// 去掉最后一个空格  
				param = str.substring(0, str.length() - 1);
			}
			StringPrintWriter strintPrintWriter = new StringPrintWriter();  
			ex.printStackTrace(strintPrintWriter);  
			
			String timeoutUrl = "/send.htm?page=error/403";
			if(ex instanceof UnauthorizedException || ex instanceof UnauthenticatedException){
				String requestType = request.getHeader("X-Requested-With");
				if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")){ 
					response.setHeader("location",request.getContextPath()+timeoutUrl);
//					response.sendError(HttpServletResponse.SC_FORBIDDEN, "session过期或无权限操作！");
					response.setHeader("sessionstatus", "unauthorized");//在响应头设置session状态  
				}else{
					return new ModelAndView("redirect:/login.htm");
				}
			}
			
			logger.error(
					"EXCEPTION INFO：\n"+
					"[REQUEST_RUL]："+ url +" \n"+
					"[REQUEST_METHOD]"+ method +" \n"+
					"[REQUEST_PARAM]："+ param +" \n"+
					"[EXCEPTION-EORR]："+ strintPrintWriter.toString());
		}
		return null;
	}   
  
    
   
 } 
